#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include "caff-test.h"

void getline(char **str, char *line){
	char *s, *e;
	s = e = *str;
	while(1){
		if(*e == '\r' && *(e+1) == '\n'){
			*e = '\0';
			e += 2;
			break;
		}else if(*e == '\0'){
			break;
		}
		e++;
	}
	if(line != NULL){
		if(strlen(s) >= LINELEN_MAX){
			strncpy(line, s, LINELEN_MAX);
		}else{
			strcpy(line, s);
		}
	}
	*str = e;
}

int usage(void){
    printf("options:\n");
    printf("  ./caff-test uuidpath\n");
    printf("NOTE:the max num of uuid:%lu\n", ULONG_MAX);
    exit(1);
}


int main(int argc, char *argv[]){
	if(argc != 2 || argv[1] == NULL){
		usage();
	}
	if(strcmp("-h", argv[1]) == 0){
		usage();
	}
	int fd, i, *mnum;
	char *buf = (char *)malloc(100);
	char *mapfile = argv[1];
	if(access(mapfile, 0) != 0){
		printf("Error:%s not exist!\n", mapfile);
		usage();
	}
	fd = open(mapfile, O_RDONLY, 0777);
	read(fd, buf, 100);
	char line[100], *key;
	getline(&buf, line);
	if(strcmp(line, FHEAD) != 0){
		printf("Error:not a caff file!\n");
		return;
	}

	getline(&buf, line);
	key = line;
	uuidtype *id = (uuidtype *)buf;
	printf("%s:%lu\n", key, *id);
}
